package cn.b.sky.form.service.impl;

import cn.b.sky.common.exception.ImeException;
import cn.b.sky.form.dao.BusinessTableRowDao;
import cn.b.sky.form.model.BusinessType;
import cn.b.sky.form.model.condition.BusinessTypeCondition;
import cn.b.sky.form.service.BusinessTableRowService;
import cn.b.sky.form.service.BusinessTypeService;
import cn.b.sky.form.service.SequenceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

@Service("businessTableRowService")
public class BusinessTableRowServiceImpl extends BusinessTableServiceImpl implements BusinessTableRowService {

	@Autowired
	protected BusinessTypeService businessTypeService;
	
	@Autowired
	protected SequenceService sequenceService;
	
	@Autowired
	protected BusinessTableRowDao businessTableRowDao;
	
	@Override
	public int insertRow(String tableName, Map<String, Object> row) {
		if(businessTableDao.getTableIsExist(tableName) == 0){
			throw ImeException.newException("TableNotExist.M", tableName);
		}
		// 获取tableName ID
		BusinessTypeCondition con = new BusinessTypeCondition();
		con.setDbTable(tableName);
		BusinessType bt = businessTypeService.getBusinessTypeByCondition(con);
		if(bt != null){
			Long id = sequenceService.generateNextValue(bt.getSiteCode(), bt.getSequenceCode());
			row.put("id", id);
			businessTableRowDao.insertRow(tableName, row);
			return id.intValue();
		}
		return 0;
	}

	@Override
	public void updateRow(String tableName, Map<String, Object> row) {
		if(businessTableDao.getTableIsExist(tableName) == 0){
			throw ImeException.newException("TableNotExist.M", tableName);
		}
		businessTableRowDao.updateRow(tableName, row);
	}

	@Override
	public void deleteRow(String tableName, int id) {
		if(businessTableDao.getTableIsExist(tableName) == 0){
			throw ImeException.newException("TableNotExist.M", tableName);
		}
		businessTableRowDao.deleteRow(tableName, id);
	}

	@Override
	public List<Map<String, Object>> selectRows(String tableName,
			Map<String, Object> parameters) {
		if(businessTableDao.getTableIsExist(tableName) == 0){
			throw ImeException.newException("TableNotExist.M", tableName);
		}
		return businessTableRowDao.selectRows(tableName, parameters);
	}

}
